import java.util.Arrays;

public class BinarySearchSolution {

    public int[] searchRange(int[] nums, int target) {
        int leftBoundIndex = binarySearchBound(nums, target, true);
        int rightBoundIndex = binarySearchBound(nums, target, false);
        if (leftBoundIndex > rightBoundIndex || leftBoundIndex < 0 || rightBoundIndex == nums.length) {
            return new int[]{-1, -1};
        } else
            return new int[]{leftBoundIndex, rightBoundIndex};
    }

    private int binarySearchBound(int[] nums, int target, boolean isLeftBound) {
        int left = 0, right = nums.length - 1;
        int ans = -1;
        while (left <= right) {
            int middle = left + ((right - left) >> 2);
            if (isLeftBound) {
                if (nums[middle] >= target) {
                    ans = middle;
                    right = middle - 1;
                } else {
                    left = middle + 1;
                }
            } else {
                if (nums[middle] <= target) {
                    ans = middle;
                    left = middle + 1;
                } else {
                    right = middle - 1;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        BinarySearchSolution solution = new BinarySearchSolution();
        System.out.println(Arrays.toString(solution.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6)));
    }
}
